//
//  KPFindPasswordViewController.swift
//  KPBaseProject
//
//  Created by 孑孓 on 2018/4/4.
//  Copyright © 2018年 Kipp. All rights reserved.
//

import UIKit
import Eureka

class KPFindPasswordViewController: FormViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        createUI()
    }
    
    //MARK: -- 创建视图
    func createUI() {
        title = "找回密码"
        
        view.backgroundColor = UIColor.white
        
        form +++ Section()
            <<< PhoneRow() { row in
                row.tag = "phoneRow"
                row.title = "手机号"
                row.placeholder = "请输入手机号"
            }
            <<< TextRow() { row in
                row.tag = "passwordRow"
                row.title = "密码"
                row.placeholder = "请输入密码"
            }
            <<< TextRow() { row in
                row.tag = "codeRow"
                row.title = "验证码"
                row.placeholder = "请输入验证码"
        }
        
//        let problemBtn = UIBarButtonItem.init(title: "修改密码", style: UIBarButtonItemStyle.plain, target: self, action: #selector(findPasswordBtnClick(btn:)))
//        navigationItem.rightBarButtonItem = problemBtn
        
        let loginBtn = UIButton.init(type: .custom)
        loginBtn.frame = CGRect.init(x: 20, y: Screen.height - 280, width: Screen.width - 40, height: 40)
        loginBtn.setTitle("登录", for: .normal)
        loginBtn.backgroundColor = UIColor.black
        loginBtn.addTarget(self, action: #selector(loginBtnClick(btn:)), for: UIControlEvents.touchUpInside)
        view.addSubview(loginBtn)
        
        let codeBtn = UIButton.init(type: .custom)
        codeBtn.frame = CGRect.init(x: 20, y: Screen.height - 200, width: Screen.width - 40, height: 40)
        codeBtn.setTitle("获取验证码", for: .normal)
        codeBtn.backgroundColor = UIColor.cyan
        codeBtn.addTarget(self, action: #selector(codeBtnClick(btn:)), for: UIControlEvents.touchUpInside)
        view.addSubview(codeBtn)
        
        let registBtn = UIButton.init(type: .custom)
        registBtn.frame = CGRect.init(x: 20, y: Screen.height - 120, width: Screen.width - 40, height: 40)
        registBtn.setTitle("找回密码", for: .normal)
        registBtn.backgroundColor = UIColor.yellow
        registBtn.addTarget(self, action: #selector(registBtnClick(btn:)), for: UIControlEvents.touchUpInside)
        view.addSubview(registBtn)
        
        let changePasswordBtn = UIBarButtonItem.init(title: "修改密码", style: UIBarButtonItemStyle.plain, target: self, action: #selector(changePasswordBtnClick(btn:)))
        navigationItem.rightBarButtonItem = changePasswordBtn
    }
    
    // MARK: Action
    @objc func changePasswordBtnClick(btn: UIButton) {
        let vc = KPChangePasswordViewController()
        self.navigationController?.pushViewController(vc)
    }

    @objc func registBtnClick(btn :UIButton) {
        let dic = form.values(includeHidden: true)
        let phoneStr = dic["phoneRow"] as! String
        let passwordStr = dic["passwordRow"] as! String
        let codeStr = dic["codeRow"] as! String
        
        if phoneStr.isEmpty {
            
        } else if passwordStr.isEmpty{
            
        } else if codeStr.isEmpty{
            
        }else{
            findPasswordRequest(phone: phoneStr, password: passwordStr, msgCode: codeStr)
        }
    }
    
    @objc func codeBtnClick(btn :UIButton) {
        let dic = form.values(includeHidden: true)
        let phoneStr = dic["phoneRow"] as! String
        if phoneStr.isEmpty {
            
        }else{
            let secret = phoneStr + "时间" + "_demo"
            getCodeRequest(phone: phoneStr, secret: secret, msgType: "forget")
        }
    }
    
    @objc func loginBtnClick(btn :UIButton) {
        let dic = form.values(includeHidden: true)
        let phoneStr = dic["phoneRow"] as! String
        let passwordStr = dic["passwordRow"] as! String
        
        if phoneStr.isEmpty {
            
        } else if passwordStr.isEmpty{
            
        }else{
            loginRequest(phone: phoneStr, password: passwordStr)
        }
    }

    
    @objc func findPasswordBtnClick(btn: UIButton) {
        let vc = KPFindPasswordViewController()
        self.navigationController?.pushViewController(vc)
    }
    
    // MARK: NetworkRequest
    // MARK: -- 获取验证码
    fileprivate func getCodeRequest(phone: String, secret: String, msgType: String){
//        startAnimating(50.size, message: "正在获取验证码...",messageFont: 16.font, type: NVActivityIndicatorType.init(rawValue: 30))
        //获取服务器时间戳
        Api.getJSONRequest(ApiType.获取服务器当前时间戳, parameters: ["phone":phone])
            .mapBaseModel()
            .subscribe(onNext: { (model) in
                KPLog("返回状态码：\(model.resultState)---返回请求结果：\(model.msg)---返回数据\(String(describing: model.data!))")
                if model.resultState == 1 {
                    let time = model.data!.string
                    let secretMd5 = phone + time! + "_demo"
                    
                    //获取验证码
                    Api.getJSONRequest(ApiType.获取验证码, parameters: ["phone":phone, "secret":secretMd5.MD5(), "msgType":msgType])
                        .mapBaseModel()
                        .subscribe(onNext: { (model) in
                            KPLog("返回状态码：\(model.resultState)---返回请求结果：\(model.msg)---返回数据\(String(describing: model.data))")
                            if model.resultState == 1{
                                
                            }else{
                                //请求失败
                            }
//                            self.stopAnimating()
                        }, onError: { (error) in
                            KPLog("错误---\(error)")
//                            self.stopAnimating()

                        })
                        .disposed(by: bag)
                }else{
                    //请求失败
                }
//                self.stopAnimating()
            }, onError: { (error) in
                KPLog("错误---\(error)")
//                self.stopAnimating()
            })
            .disposed(by: bag)
    }
    
    // MARK: -- 找回密码
    fileprivate func findPasswordRequest(phone: String, password: String, msgCode: String){
//        startAnimating(50.size, message: "正在注册...",messageFont: 16.font, type: NVActivityIndicatorType.init(rawValue: 30))
        Api.postJSONRequest(ApiType.忘记密码, parameters: ["phone":phone, "password":password, "msgCode":msgCode])
            .mapBaseModel()
            .subscribe(onNext: { (model) in
                KPLog("返回状态码：\(model.resultState)---返回请求结果：\(model.msg)---返回数据\(String(describing: model.data!))")
                if model.resultState == 1 {
                    KPLog("成功")
//                    self.stopAnimating()
                }else{
                    KPLog("失败")
//                    self.stopAnimating()
                }
            }, onError: { (error) in
//                self.stopAnimating()
            })
            .disposed(by: bag)
    }
    
    // MARK: -- 登录
    fileprivate func loginRequest(phone: String, password: String){
//        startAnimating(50.size, message: "正在注册...",messageFont: 16.font, type: NVActivityIndicatorType.init(rawValue: 30))
        Api.postJSONRequest(ApiType.登录, parameters: ["account":phone, "password":password])
        .mapBaseModel()
            .subscribe(onNext: { (model) in
                KPLog("返回状态码：\(model.resultState)---返回请求结果：\(model.msg)---返回数据\(String(describing: model.data!))")
                if model.resultState == 1 {
                    KPLog("成功")
//                    self.stopAnimating()
                }else{
                    KPLog("失败")
//                    self.stopAnimating()
                }

            }, onError: { (error) in
//                self.stopAnimating()
            })
        .disposed(by: bag)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
